package com.treeHole.treeHoleServer.service.impl;

import com.treeHole.treeHoleServer.mapper.CommentMapper;
import com.treeHole.treeHoleServer.mapper.PostMapper;
import com.treeHole.treeHoleServer.pojo.Comment;
import com.treeHole.treeHoleServer.pojo.RequestDataDTO.PostDeleteCommentDTO;
import com.treeHole.treeHoleServer.pojo.ResultDataDTO.ResultCommentDTO;
import com.treeHole.treeHoleServer.service.CommentService;
import com.treeHole.treeHoleServer.utils.RandomUsernameGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    CommentMapper commentMapper;

    @Autowired
    PostMapper postMapper;

    @Override
    public int userLikeComment(Integer userId, Integer commentId) {
        log.info("服务层收到用户点赞评论请求");
        return commentMapper.insertLikeCommentRecord(commentId,userId, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

    }

    @Override
    public int userUnlikeComment(Integer userId, Integer commentId) {
        log.info("服务层收到用户取消点赞请求");
        return commentMapper.deleteLikeCommentRecord(commentId,userId);
    }

    @Override
    public ResultCommentDTO userCreateComment(PostDeleteCommentDTO postDeleteCommentDTO) {
        Integer userId = postDeleteCommentDTO.getUserId();
        Integer postId = postDeleteCommentDTO.getPostId();
        Integer type=postDeleteCommentDTO.getType();


        String userName;
        //先判断发评论的人是否是帖主,如果是,使用post表中的username
        Integer authorId=postMapper.getAuthorIdFromPostId(postId);
        if(Objects.equals(authorId, userId)){
            userName=postMapper.getAuthorNameFromPostId(postId);
            log.info("服务层处理评论发布:帖主发布评论,使用post表中的userName:{}",userName);
        }else{
            //若不是帖主,在数据库中寻找该用户在该帖子下是否评论过,如果是,使用之前的随机名称,如果没有,新生成名称
            userName= commentMapper.getSpecificUserNameInPost(userId,postId);
            log.info("服务层处理评论发布:非帖主发布评论,查找comment表中的userName:{}",userName);
            if(userName== null){
                List<String> existUserName=commentMapper.getAllUserNameInPost(postId);
                userName= RandomUsernameGenerator.getDifName(new HashSet<String>(existUserName) );
                log.info("服务层处理评论发布:非帖主第一次发布评论,生成新的userName:{}",userName);
            }

        }

        Integer reUserId=0;
        if(type==1&&!postDeleteCommentDTO.getReplyUserName().isEmpty()){
            reUserId=commentMapper.getUserIdFromUserName(postDeleteCommentDTO.getReplyUserName(), postId);

        }
        log.info("服务层收到创建评论请求,评论的用户id:{},评论的用户昵称:{},回复的用户id:{},回复的用户昵称:{}",
                userId,userName,reUserId,postDeleteCommentDTO.getReplyUserName());
        Comment insertComment=new Comment(0, postId,userId,userName,
                postDeleteCommentDTO.getContent(),
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
                Boolean.FALSE,
                postDeleteCommentDTO.getType(),
                postDeleteCommentDTO.getCmtCmtId(),
                reUserId);
        int resultCode = commentMapper.postNewComment(insertComment);
        log.info("服务层处理了发布评论请求,处理结果:{},添加的评论id:{}",resultCode,insertComment.getCommentId());
        return new ResultCommentDTO(
                insertComment.getCommentId(),
                userName,postId,
                System.currentTimeMillis(),
                postDeleteCommentDTO.getContent(),
                Boolean.FALSE,
                0,
                postDeleteCommentDTO.getType(),
                postDeleteCommentDTO.getCmtCmtId(),
                postDeleteCommentDTO.getReplyUserName());
    }

    @Override
    public int userDeleteComment(PostDeleteCommentDTO postDeleteCommentDTO) {
        log.info("服务层收到删除评论请求");
        return commentMapper.deleteComment(postDeleteCommentDTO.getCmtId());
    }

    @Override
    public List<ResultCommentDTO> getUserComments(Integer userId, Integer page) {
        List<Comment> originCommentList=commentMapper.getUserComment(userId,page*20);
        List<ResultCommentDTO> resultCommentDTOList=new ArrayList<ResultCommentDTO>();
        // 创建 SimpleDateFormat 对象，指定日期时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //遍历获取到的原始评论列表，将其转化为返回给客户端的评论数据传输类型
        for (Comment c : originCommentList) {
            ResultCommentDTO reCmtDTO=new ResultCommentDTO();
            reCmtDTO.setCmtId(c.getCommentId());
            reCmtDTO.setCmtName(c.getUserName());
            reCmtDTO.setPostId(c.getPostId());
            //将数据库中的时间字符串类型转化为时间戳
            try {
                long timestamp=sdf.parse(c.getCommentDate()).getTime();
                reCmtDTO.setCmtTime(timestamp);
            }catch (ParseException e){
                log.error(e.getMessage());
            }

            reCmtDTO.setCmtContent(c.getContent());

            //在commentLike表中查询用户id与用户自身评论id的数据,如果为空说明用户未点赞自己的评论
            List<Integer> cmtLikeRecordList=commentMapper.getUserIsLikeComment(userId,c.getCommentId());
            if(cmtLikeRecordList.isEmpty()){
                reCmtDTO.setIsLike(Boolean.FALSE);
            }else reCmtDTO.setIsLike(Boolean.TRUE);

            //查找当前评论的点赞数
            reCmtDTO.setCmtLikeCount(commentMapper.getCommentLikeCount(c.getCommentId()));

            reCmtDTO.setType(c.getCommentType());
            reCmtDTO.setCmtCmtId(c.getReCommentId());
            if(c.getReUserId()!=0){
                reCmtDTO.setReplyUserName(commentMapper.getSpecificUserNameInPost(c.getReUserId(),c.getPostId()));
            }else reCmtDTO.setReplyUserName("");
            resultCommentDTOList.add(reCmtDTO);
        }
        return resultCommentDTOList;
    }
}
